package com.jokerku.mini.schedule.sharding;

import com.jokerku.mini.schedule.spi.JobServiceLoader;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author: guzq
 * @CreateTime: 2023/06/20 14:57
 * @Description: 分片策略工厂
 * @Version: 1.0
 */
public class ShardingStrategyFactory {

    private static final Map<String, ShardingStrategy> STRATEGY_MAP = new ConcurrentHashMap<>();

    static {
        List<ShardingStrategy> shardingStrategies = JobServiceLoader.load(ShardingStrategy.class);
        shardingStrategies.forEach(ShardingStrategyFactory::putShardingStrategy);
    }

    public static void putShardingStrategy(ShardingStrategy shardingStrategy) {
        STRATEGY_MAP.put(shardingStrategy.getType(), shardingStrategy);
    }

    public static ShardingStrategy getShardingStrategy(final String type) {
        return Optional.ofNullable(STRATEGY_MAP.get(type))
                .orElseThrow(() -> new RuntimeException(String.format("Cannot find sharding strategy using type '%s'.", type)));
    }

}
